package com.markerhub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.lang.Const;
import com.markerhub.entity.AppUserSetting;
import com.markerhub.mapper.AppUserMapper;
import com.markerhub.service.AppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 */
@Slf4j
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUserSetting>
    implements AppUserService{

    @Resource
    HttpSession httpSession;

    @Override
    public AppUserSetting login(LoginDto loginDto) {
        AppUserSetting appUser= this.getOne(new QueryWrapper<AppUserSetting>().eq("username",loginDto.getUsername()));

        // 校验用户名和密码
        Assert.notNull(appUser,"用户名不能为空");
        //Assert.isTrue(appUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword())),"用户名或密码错误");
        //更新一下最后登录的时间
        //appUser.setLastLogin(LocalDateTime.now());
        this.updateById(appUser);
        return appUser;
    }


    @Override
    public AppUserSetting getCurrentUser() {
        return this.getById(getCurrentUserId());
    }

    @Override
    public long getCurrentUserId() {
        Long userId = (Long) httpSession.getAttribute(Const.USER_KEY);
        log.info("userId userId {userId} {userId}",userId);
        return userId == null ? -1 : userId;
    }

    @Override
    public AppUserSetting getUser(String id) {
        AppUserSetting appUser= this.getOne(new QueryWrapper<AppUserSetting>().eq("id",id));
        // 校验用户名和密码
        Assert.notNull(appUser,"用户名不能为空");
        //Assert.isTrue(appUser.getPassword().equals(SecureUtil.md5(loginDto.getPassword())),"用户名或密码错误");
        //更新一下最后登录的时间
        //this.updateById(appUser);

        return appUser;
    }

    @Override
    public int updateUser(AppUserSetting userSetting) {

        int number = baseMapper.updateById(userSetting);
        return number;

    }

    @Override
    public int delUserId(List<String> ids) {
        for (int k=0;k<ids.size();k++){
            Map<String, Object> map = new HashMap<>();
            map.put("id",ids.get(k));
            int flag = baseMapper.deleteByMap(map);
            if (k==ids.size()-1){
                return flag;
            }
        }
        return 1;
    }


}




